import { useCallback, useEffect, useRef, useState } from "react";
import { useSetUrlSearchParam, useUrlQueryParam } from "./url";
import { useProject } from "./project";
// import { URLSearchParamsInit } from "react-router-dom";
export const isFalsy = (value: unknown) => (value === 0 ? false : !value);
export const isVoid = (value: unknown) =>
  value === undefined || value === null || value === "";
//去除对象中的空属性
export const cleanObject = (object: { [key: string]: unknown }) => {
  let result = { ...object };
  Object.keys(result).forEach((key) => {
    const value = object[key];
    if (isVoid(value)) {
      delete result[key];
    }
  });
  return result;
};

export const useMount = (callback: () => void) => {
  useEffect(() => {
    callback();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
};

// export const debounce = (callback, delay) => {
//   let timeout;
//   console.log(12);
//   timeout = setTimeout(() => {
//     callback()
//   }, delay);
//   return () => {
//     if(timeout) {
//       clearTimeout(timeout)
//     }
//   }
// }

export const useDebounce = <T>(value: T, delay?: number): T => {
  const [debouncedValue, setDebouncedValue] = useState(value);
  useEffect(() => {
    let timeout = setTimeout(() => setDebouncedValue(value), delay);
    return () => {
      if (timeout) {
        clearTimeout(timeout);
      }
    };
  }, [value, delay]);
  return debouncedValue;
};

export const useArray = <T>(person: T[]) => {
  const [value, setValue] = useState<T[]>(person);
  const add = (val: T) => {
    setValue([...value, val]);
  };
  const removeIndex = (index: number) => {
    let arr = [...value];
    arr.splice(index, 1);
    // console.log('arr', arr);
    setValue(arr);
  };
  const clear = () => {
    setValue([]);
  };
  return {
    value,
    add,
    removeIndex,
    clear,
    setValue,
  };
};

export const useDocumentTitle = (title: string, keepOnUnmount = false) => {
  const oldTitle = useRef(document.title).current;
  useEffect(() => {
    document.title = title;
  }, [title]);
  useEffect(() => {
    return () => {
      if (!keepOnUnmount) {
        // console.log(oldTitle);
        document.title = oldTitle;
      }
    };
  }, [keepOnUnmount, oldTitle]);
};

export const resetRoute = () => (window.location.href = window.location.origin);

export const useMountedRef = () => {
  const mountedRef = useRef(false);
  useEffect(() => {
    mountedRef.current = true;
    return () => {
      mountedRef.current = false;
    };
  });
  return mountedRef;
};

export const useProjectModal = () => {
  const [projectCreate, setProjectCreate] = useUrlQueryParam(["projectCreate"]);
  const [editingProjectId, setEditingProjectId] = useUrlQueryParam([
    "editingProjectId",
  ]);
  const { data: editingProject, isLoading } = useProject(
    Number(editingProjectId.editingProjectId)
  );
  const open = useCallback(
    () => setProjectCreate({ projectCreate: true }),
    [setProjectCreate]
  );
  const setUelParams = useSetUrlSearchParam();
  const close = () => setUelParams({ projectCreate: "", editingProjectId: "" });
  // const close = () => {
  //   setProjectCreate({projectCreate: undefined})
  //   setEditingProjectId({ editingProjectId:'undefined' })
  // }
  const startEdit = (id: number) =>
    setEditingProjectId({ editingProjectId: id });
  return {
    projectCreate:
      projectCreate.projectCreate === "true" ||
      Boolean(editingProjectId.editingProjectId),
    open,
    close,
    startEdit,
    editingProject,
    isLoading,
  };
};
/**
 * 传入一个对象，和键集合，返回对应的对象中的键值对
 * @param obj
 * @param keys
 */
export const subset = <
  O extends { [key in string]: unknown },
  K extends keyof O
>(
  obj: O,
  keys: K[]
) => {
  const filteredEntries = Object.entries(obj).filter(([key]) =>
    keys.includes(key as K)
  );
  return Object.fromEntries(filteredEntries) as Pick<O, K>;
};
